from urllib.request import urlopen
from urllib.request import Request
from urllib.parse import urlencode
from urllib.parse import quote_plus


def play(text, per=0, spd=5, pit=5, vol=5, aue=3):
    # token = fetch_token()
    # 此处使用您自己的roken值
    token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    tex = quote_plus(text)  # 此处TEXT需要两次urlencode
    # print(tex)
    params = {'tok': token, 'tex': tex, 'per': int(per), 'spd': int(spd), 'pit': int(pit), 'vol': int(vol), 'aue': int(aue), 'cuid': "123456PYTHON",
              'lan': 'zh', 'ctp': 1}  # lan ctp 固定参数

    data = urlencode(params)
    # print('test on Web Browser' + TTS_URL + '?' + data)

    req = Request('http://tsn.baidu.com/text2audio', data.encode('utf-8'))
    f = urlopen(req)
    result_str = f.read()

    with open('/home/mhc/result.mp3', 'wb') as of:
        of.write(result_str)


if __name__ == '__main__':
    play("miha")


